package com.service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Future;

import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import com.model.OrderDetail;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCollapser;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;

@Component
public class OrderDetailService {

	// 合并处理收集5秒内的请求
	@HystrixCollapser(batchMethod = "getMoreOrderDetails",collapserProperties = {@HystrixProperty(name ="timerDelayInMilliseconds",value = "5000")})
	public Future<OrderDetail> getOneOrderDetail(String id) {
		System.out.println("in getOneOrderDetail");
		return null;
	}

	@Bean
	@LoadBalanced
	public RestTemplate getRestTemplate()
	{
		return new RestTemplate();   
	}

	
	@HystrixCommand
	public List<OrderDetail> getMoreOrderDetails(List<String> orderIds) {
		System.out.println("in getMoreOrderDetails," + orderIds.size());
		List<OrderDetail> list = new ArrayList<OrderDetail>();
		
		RestTemplate template = getRestTemplate();
		
		for (String orderId : orderIds) {
			OrderDetail orderDetail = new OrderDetail();  
			orderDetail = template.getForObject("http://localhost:1111/getOrderDetailById/{orderId}", OrderDetail.class,orderId);
			list.add(orderDetail);
		}
		return list;
	}
}
